package com.simple.util;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.context.support.AbstractMessageSource;

import com.simple.util.common.LocaleUtil;
import com.simple.util.common.Utils;

/**
 * MessageSource implementation that reads the messages from a Datasource
 */
public class DataSourceMessageSource extends AbstractMessageSource {
    private static final Logger LOG = Logger.getLogger(DataSourceMessageSource.class);
    
    /** used for filtering certain groups of messages (optional) */
    private String[] basenames = new String[0];
    
    //locale-key-value
    private Map<String,Map<String, String>> pkMap;
    
    
    /**
     * Set a single basename, must match exactly with value in tableName.basenameColumn
     * 
     * @param basename
     *            the single basename
     * @see #setBasenames
     */
    public void setBasename(final String basename) {
        setBasenames(new String[] { basename });
    }

    /**
     * Set an array of basenames
     * 
     * @param basenames
     *            an array of basenames
     * @see #setBasename
     */
    public void setBasenames(final String[] basenames) {
        this.basenames = Utils.copyArray(basenames);
    }

    @Override
    protected  MessageFormat resolveCode(final String code, final Locale locale) {
        if(pkMap == null){
            pkMap = TbResourceLoad.getInstance().getMap(basenames);
        }
        
        final String validLocale = LocaleUtil.getValidLocale(locale);
        
        MessageFormat messageFormat = null;
        if(pkMap.containsKey(validLocale) && pkMap.get(validLocale).containsKey(code)){
            final String msg = pkMap.get(validLocale).get(code);
            messageFormat = createMessageFormat(msg, locale);
        }
        
        if (messageFormat == null) {
            LOG.info("could not resolve [" + code + "] for locale [" + validLocale + "]");
        }

        return messageFormat;
    }

}